import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpRequest } from "../../../service/httpRequest";
import { HideElementService } from "../../../service/hideElement.service";
import { flyIn } from '../../../animations/fly-in';
import { GlobalVariable } from '../../../global.config';
import { ModalDirective } from 'ng2-bootstrap/modal';

@Component({
  selector: 'app-groups',
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.css'],
  animations: [
    flyIn
  ]
})
export class GroupsComponent implements OnInit {
  elc = {a:'群组新增',e:'群组编辑',d:'群组删除'};
  @ViewChild('myModal') public myModal:ModalDirective;
  buttonType:number = 0;
  disabled:string = '';
  model = {name:'',man:'',phone:''};
  selectedId:string = '';

  tool = GlobalVariable.tooltip;
  data:any;
  keyword:any;
  productsData:any;

  constructor(private httpRequest:HttpRequest,private he:HideElementService) {
    this.elc = this.he.hideElement(this.elc);
  }

  ngOnInit() {
    this.getData();    
  }

  getData(){
    this.httpRequest.sendGet('device/group/list2').subscribe(res=>{
      this.data = res.result;
    },err=>console.log(err));
  }



  newModal(){
    this.buttonType=1;
    this.model = {name:'',man:'',phone:''};
    this.myModal.show();
  }


  confirmNew(){
    this.httpRequest.sendPost('device/group/save',{
      name: this.model.name,     
      lxr: this.model.man,
      lxdh: this.model.phone
    }).subscribe(res=>{
      alert("群组创建成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('群组创建失败!');this.disabled='';console.log(err)});
  }

  editModal(item){
    this.buttonType=2;
    this.selectedId = item.id;
    this.model = {name:item.name,man:item.lxr,phone:item.lxdh};
    this.myModal.show();
  }

  confirmEdit(){
    this.httpRequest.sendPut('device/group/update/'+this.selectedId,{
      name: this.model.name,      
      lxr: this.model.man,
      lxdh: this.model.phone
    }).subscribe(res=>{
      alert("群组修改成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('群组修改失败!');this.disabled='';console.log(err)});
  }

  deleteModal(item){
    this.buttonType=3;
    this.selectedId = item.id;
    this.model.name = item.name;
    this.myModal.show();
  }

  confirmDelete(){
    this.httpRequest.sendDelete('device/group/'+this.selectedId).subscribe(res=>{
      alert("群组删除成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('群组删除失败!');this.disabled='';console.log(err)});
  }

}
